package controllers

import (
	"LearnProject/helpers"
	"LearnProject/lib"
	"fmt"
	"net/http"
	"strconv"
)

func Index(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w,"welcome home page site")
}


//
func PostIndex(w http.ResponseWriter, r *http.Request) {
	id := r.PostFormValue("id")
	cid, err := strconv.Atoi(id)
	if err != nil {
		cid = 0
	}
	var postItem = lib.GetPostItem(cid)
	helpers.JsonOut(w, postItem)
}

//标准 添加
func PostSave(w http.ResponseWriter, r *http.Request) {
	title := r.PostFormValue("title")
	if title == "" {
		helpers.JsonErrorOut(w, nil, 10000)
		return
	}

	id := r.PostFormValue("id")
	cid, err := strconv.Atoi(id)
	if err != nil {
		cid = 0
	}

	//保存并输出
	postId := lib.SavePost(cid, title)
	returnData  := make(map[string]int)
	returnData["id"] = postId
	helpers.JsonOut(w, returnData)
}

//标准 删除
func PostDelete(w http.ResponseWriter, r *http.Request) {
	id := r.PostFormValue("id")
	cid, err := strconv.Atoi(id)
	if err != nil {
		cid = 0
	}

	returnData  := make(map[string]int)
	gormObj := lib.PostDelete(cid)
	if gormObj.RowsAffected > 0 {
		helpers.JsonOut(w, returnData)
		return
	}

	helpers.JsonErrorOut(w, returnData, 10004)
}

//标准 列表多条
func PostList(w http.ResponseWriter, r *http.Request) {
	status := r.URL.Query().Get("status")
	statusNumber, err := strconv.Atoi(status)
	if err != nil {
		statusNumber = 0
	}
	var postItem = lib.GetPostList(statusNumber)
	helpers.JsonOut(w, postItem)
}

//标准 单条
func PostItem(w http.ResponseWriter, r *http.Request) {
	id := r.URL.Query().Get("id")
	cid, err := strconv.Atoi(id)
	if err != nil {
		cid = 0
	}
	var postItem = lib.GetPostItem(cid)
	helpers.JsonOut(w, postItem)
}